//
//  YPLogonViewController.m
//  ChengHuiTong
//
//  Created by KiVen on 15/11/12.
//  Copyright © 2015年 张文权. All rights reserved.
//

#import "YPLogonViewController.h"
#import "YPRegistViewController.h"
#import "YPPerfectInformationViewController.h"
#import "MainTabbarViewController.h"
#import "YPForgotPasswordViewController.h"

@interface YPLogonViewController (){
    
    UILabel * _errorLabel;
    
//    用户名输入框
    UITextField * _userNameTextField;
//    密码输入框
    UITextField *_passWordTextField;
    NSUInteger _lastSelectedIndex;

}
@property(readonly, nonatomic) NSUInteger lastSelectedIndex;

@end

@implementation YPLogonViewController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
   
    [MobClick beginLogPageView:@"登录"];

}
- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:YES];
    
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    
    [MobClick endLogPageView:@"登录"];

}

- (void)viewDidLoad {
    [super viewDidLoad];

    {
        UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        [leftButton addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        [leftButton setTitle:@"返回" forState:UIControlStateNormal];
        UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.navigationItem.leftBarButtonItem = leftItem;
    }


    [self creatLogonView];

}
- (void)creatLogonView{
    
//    大的背景图
    _backGroudScrollView = [[TPKeyboardAvoidingScrollView alloc]init];
    _backGroudScrollView.frame = CGRectMake(0, 0,SCREEN_WIDTH , SCREEN_HEIGHT);
    _backGroudScrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT);
    _backGroudScrollView.scrollEnabled = NO;
    [self.view addSubview:_backGroudScrollView];
    
    UIButton * backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(15, 24, 40, 40);
    [backButton setTitleColor:[UIColor darkGrayColor] forState:0];
    [backButton setTitle:@"返回" forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_backGroudScrollView addSubview:backButton];
    

    UIImage *image = [UIImage imageNamed:@"cehnghuitong"];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake((SCREEN_WIDTH - 200)/2.f, 10, 200, image.size.height/image.size.width*200)];
    imageView.image = image;
    imageView.centerX = _backGroudScrollView.centerX;
    imageView.top = backButton.bottom + autoScaleH(40);
    [_backGroudScrollView addSubview:imageView];
    
    
    _userNameTextField = [[UITextField alloc]initWithFrame:CGRectMake(autoScaleW(15), imageView.bottom + autoScaleH(60), SCREEN_WIDTH - autoScaleW(15)*2, 45)];
    _userNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    [self configTextField:_userNameTextField leftImage:@"zhanghao" placeHolder:@"手机/邮箱/用户名"];
    [_backGroudScrollView addSubview:_userNameTextField];
    
    
    _passWordTextField = [[UITextField alloc]initWithFrame:CGRectMake(_userNameTextField.left, _userNameTextField.bottom - 1, _userNameTextField.width,_userNameTextField.height)];
    [self configTextField:_passWordTextField leftImage:@"mimasuo" placeHolder:@"登录密码"];
    [_backGroudScrollView addSubview:_passWordTextField];
    
    
    UIButton *loginBtn = [UIButton creatWithFrame:CGRectMake(_userNameTextField.left, _passWordTextField.bottom + 20, _userNameTextField.width, _userNameTextField.height)
                                             font:[UIFont systemFontOfSize:16]
                                             text:@"登录"
                                           action:@selector(loginButtonClick)
                                           target:self];
    loginBtn.backgroundColor = kColor_AppNavColor;
    [_backGroudScrollView addSubview:loginBtn];
    
    
    UIButton *forgetBtn = [UIButton creatWithFrame:CGRectMake(0, loginBtn.bottom, 75, 40)
                                             font:[UIFont systemFontOfSize:15]
                                             text:@"忘记密码?"
                                        textColor:[UIColor darkGrayColor]
                                           action:@selector(forgetButtonClick)
                                           target:self];
    forgetBtn.right = loginBtn.right;
    [_backGroudScrollView addSubview:forgetBtn];
    
    
    
    UIButton *registerBtn = [UIButton creatWithFrame:CGRectMake((SCREEN_WIDTH - 120)/2.f, _backGroudScrollView.height - autoScaleH(40) - 40, 120, 40)
                                              font:[UIFont systemFontOfSize:15]
                                              text:@"马上注册"
                                         textColor:kColor_AppNavColor
                                            action:@selector(registButtonClick)
                                            target:self];
    registerBtn.layer.cornerRadius = 3;
    [registerBtn setBorderWithColor:kColor_AppNavColor borderWidth:1];
    [_backGroudScrollView addSubview:registerBtn];
    
    

    
}

- (void)configTextField:(UITextField *)textField
              leftImage:(NSString *)imageStr
            placeHolder:(NSString *)placeHolder{
    
    textField.backgroundColor = [UIColor whiteColor];
    textField.layer.borderColor = colorWithRGB(200, 200, 200).CGColor;
    textField.layer.borderWidth = 0.5;
    
    UIImage *image = [UIImage imageNamed:imageStr];
    UIView *leftView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 55, textField.height)];
    [leftView addLineWithFrame:CGRectMake(leftView.right - 10, 15, 0.5, leftView.height - 30) color:colorWithRGB(210, 210, 210)];
    UIImageView *imageV = [[UIImageView alloc]initWithImage:image];
    [imageV sizeToFit];
    imageV.center = leftView.center;
    imageV.left -= 5;
    [leftView addSubview:imageV];
    textField.leftView = leftView;
    textField.leftViewMode = UITextFieldViewModeAlways;
    textField.placeholder = placeHolder;
    textField.font = [UIFont systemFontOfSize:15];
    
    if (textField == _passWordTextField) {
        UIButton *pswBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 40, _passWordTextField.height)];
        [pswBtn setImage:[UIImage imageNamed:@"xianshi"] forState:0];
        [pswBtn setImage:[UIImage imageNamed:@"yincang"] forState:UIControlStateSelected];
        pswBtn.selected = YES;
        textField.secureTextEntry = YES;
        [pswBtn addTarget:self action:@selector(showPsw:) forControlEvents:UIControlEventTouchUpInside];
        textField.rightView = pswBtn;
        textField.rightViewMode = UITextFieldViewModeAlways;
    }
    
}

#pragma mark - buttpnClick
- (void)showPsw:(UIButton *)btn{
    
    btn.selected = !btn.selected;
    
    _passWordTextField.secureTextEntry = btn.selected;
}
- (void)backButtonClick{
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
    
}

- (void)registButtonClick{
    
    YPRegistViewController * registVC = [[YPRegistViewController alloc]init];
    registVC.completBlock = ^(NSString *token){
        if(self.completBlock)self.completBlock(TOKEN);
    };
    [self.navigationController pushViewController:registVC animated:YES];
    
    NSLog(@"注册");
}

- (void)forgetButtonClick{
    
    YPForgotPasswordViewController * forgotPasswordVC = [[YPForgotPasswordViewController alloc]init];
    
    forgotPasswordVC.title=@"忘记密码";
    
    
    forgotPasswordVC.popVC=^{
        
        [self.navigationController popViewControllerAnimated:YES];
        
        
    };
    
    forgotPasswordVC.isSetPassword=NO;
    
    [self.navigationController pushViewController:forgotPasswordVC animated:YES];
    
    
}

- (void)loginButtonClick{
    
    if (_userNameTextField.text.length <1) {
        
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入用户名"];
        return;
    }
    if (_passWordTextField.text.length<1) {
        [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"请输入密码"];
        return;
    }


    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    [RequestModel loginSuccessWithname:[GetCodeString getCodeWithString:_userNameTextField.text] andPwd:[GetCodeString getCodeWithString:_passWordTextField.text] Block:^(id responseDictionary) {
        
        NSLog(@"%@",responseDictionary);
        
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([responseDictionary[@"status"] intValue]== 0) {
            
            
            YPShareAccountInfo*userinfo=[YPShareAccountInfo shareAccountInfo];
            
            
            userinfo.g_status=responseDictionary[@"g_status"];
            
            userinfo.g_password=responseDictionary[@"g_password"];
            
            if ([responseDictionary[@"g_status"]intValue]==0) {
                
                
                [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"CoreLockPWDKey"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
            }else if ([responseDictionary[@"g_status"]intValue]==1){
                
                [[NSUserDefaults standardUserDefaults] setObject:responseDictionary[@"g_password"] forKey:@"CoreLockPWDKey"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                
                
            }
            
            userinfo.userName =responseDictionary[@"username"];
            [userinfo setDataWithDic:responseDictionary];
            [userinfo saveData];
            [self sendDevice_token];
            
            [self dismissViewControllerAnimated:YES completion:^{
                
                if (self.completBlock) {
                    self.completBlock(TOKEN);
                }
                
            }];
            
            
        }else if ([responseDictionary[@"status"] intValue]== 1102){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"账户或密码错误"];
        }else if ([responseDictionary[@"status"] intValue]== 1103){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"此账户不存在"];
        }else if ([responseDictionary[@"status"] intValue]== 1104){
            
            [YRProgressHUD autoShowHUDAddedTo:self.view withText:@"此账户被锁定"];
        }

        
    } failBlock:^(id obj) {
        
    }];

            
}

- (void)sendDevice_token{
    
    YPDeviceBin * bin = [[YPDeviceBin alloc]init];
    bin.token = [YPShareAccountInfo shareAccountInfo].token;
    
    bin.device_token = [LGToolMethods getUserDefaultsObjForKey:@"deviceKey"];
    
    NSLog(@"%@",[LGToolMethods getUserDefaultsObjForKey:@"deviceKey"]);
    
    [YPHttpRequestMethod sendAsyRequestURL:CMD_SEND_DEVICE_TOKEN withData:[bin dictionaryValue] withCompletionBlock:^(NSDictionary *responseDictionary) {
        
        NSLog(@"responseDictionary=%@",responseDictionary);
        
        
    } withFailedBlock:^(NSError *error) {
        
        
    } withIndicator:NO atView:self.view];

}

- (void)backAction{

    [self.navigationController dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIWindow * window = [UIApplication sharedApplication].keyWindow;
    
    MainTabbarViewController * mainTabbar =(MainTabbarViewController *) window.rootViewController;
    [mainTabbar setSelectedIndex:0];

}

- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleDefault;
    
}



@end
